package com.education.service.impl;

import com.education.common.Const;
import com.education.common.JsonData;
import com.education.common.RequestHolder;
import com.education.dao.AdminMapper;
import com.education.dao.FunctionMapper;
import com.education.dao.RoleFunctionMapper;
import com.education.dao.RoleMapper;
import com.education.pojo.Admin;
import com.education.pojo.Function;
import com.education.pojo.Role;
import com.education.pojo.RoleFunction;
import com.education.service.IDbaService;
import com.education.utils.JsonMapper;
import com.education.utils.MD5Util;
import com.education.vo.AdminInfoVo;
import com.education.vo.FunctionAdminVo;
import com.education.vo.RoleAdminVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 林心晨
 * @Title:
 * @Package
 * @Description:
 * @date create in 4.28  15:54
 */
@Service("iDbaService")
@Transactional
public class DbaServiceImpl implements IDbaService {

    private static Logger logger = LoggerFactory.getLogger(DbaServiceImpl.class);

    @Autowired
    private AdminMapper adminMapper ;

    @Autowired
    private RoleMapper roleMapper ;

    @Autowired
    private FunctionMapper functionMapper ;

    @Autowired
    private RoleFunctionMapper roleFunctionMapper ;

    @Resource
    private SysCacheService sysCacheService;

    /**
     * 对admin集合进行分页
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo meteAdminList(int pageNum,int pageSize){
        String orderDesc = "a_id" + " desc";
        PageHelper.startPage(pageNum,pageSize,orderDesc);
        List<AdminInfoVo> adminInfoVoList = Lists.newArrayList();
        List<Admin> admins = adminMapper.selectAll();
        for (Admin adminItem : admins){
            AdminInfoVo productListVo = assembleAdminVo(adminItem);
            //将封装好的list添加到集合中
            adminInfoVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(admins);
        pageInfo.setList(adminInfoVoList);
        return pageInfo;
    }

    public PageInfo deletedList(int pageNum,int pageSize){
        String orderDesc = "a_id" + " desc";
        PageHelper.startPage(pageNum,pageSize,orderDesc);
        List<AdminInfoVo> adminInfoVoList = Lists.newArrayList();
        List<Admin> admins = adminMapper.selectAllByDeleted();
        for (Admin adminItem : admins){
            AdminInfoVo productListVo = assembleAdminVo(adminItem);
            //将封装好的list添加到集合中
            adminInfoVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(admins);
        pageInfo.setList(adminInfoVoList);
        return pageInfo;
    }


    /**
     * 按条件查询
     * @param pageNum   当前页码
     * @param pageSize  每页显示的条数
     * @param dateMin   最小时间约束
     * @param dateMax   最大时间约束
     * @param adminName 按名字
     * @return  返回分页后的数据
     */
    public PageInfo conditionQuery(int pageNum,int pageSize,String dateMin,String dateMax,String adminName){
        Date min = null;
        Date max = null;
        StringBuffer sb;
        List<AdminInfoVo> adminInfoVoList ;
        List<Admin> admins ;
        PageInfo pageInfo = null;
        String adminN = "";
        String orderDesc = "a_id" + " desc";
        PageHelper.startPage(pageNum,pageSize,orderDesc);
        if (StringUtils.isNoneBlank(dateMin)&& StringUtils.isNoneBlank(dateMax)){
            DateTime minDate = new DateTime(dateMin);
            DateTime maxDate = new DateTime(dateMax);
            DateTime minDateTime = minDate.millisOfDay().withMaximumValue();
            DateTime maxDateTime = maxDate.plus(1).millisOfDay().withMaximumValue();
            min = minDateTime.toDate() ;
            max = maxDateTime.toDate();
        }
        if (StringUtils.isNoneBlank(adminName)){
            sb = new StringBuffer().append("%").append(adminName).append("%");
            adminN = sb.toString();
        }
        admins = adminMapper.selectByTime(min, max, adminN);
        if (admins != null){
            adminInfoVoList = Lists.newArrayList();
            for (Admin adminItem : admins){
                AdminInfoVo adminInfoVo = assembleAdminVo(adminItem);
                adminInfoVoList.add(adminInfoVo);
            }
            pageInfo = new PageInfo();
            pageInfo.setList(adminInfoVoList);
        }
        return pageInfo ;
    }

    /**
     * 删除id对应的admin
     * @param id
     * @return
     */
    public Map<String,Object> deleteAdminOne(String id){
        Map<String,Object> map ;
        if (StringUtils.isBlank(id)){
            map = Maps.newHashMap();
            map.put("msg","参数异常");
            return map ;
        }
        Integer adminId = Integer.parseInt(id);
        int rowCount = adminMapper.deleteAdminByStateId(adminId);
        if (rowCount <= 0){
            map = Maps.newHashMap();
            map.put("msg","不可删除");
            return map ;
        }
        map = Maps.newHashMap();
        map.put("msg","删除成功");
        return map ;
    }

    public Map<String,Object> adminAdd(Admin admin){
        Map<String,Object> map ;
        admin.setaPassword(MD5Util.MD5EncodeUtf8(admin.getaPassword()));
        admin.setDeleted(0);
        int rowCount = adminMapper.insert(admin);
        if (rowCount > 0){
            map = Maps.newHashMap() ;
            map.put("msg","添加成功");
            return map ;
        }
        map = Maps.newHashMap() ;
        map.put("msg","添加失败");
        return map ;
    }

    public Map<String,Object> delete(String[] id){
        Map<String,Object> map ;
        List<Integer> idList = Lists.newLinkedList();
        for (String item : id){
            idList.add(Integer.valueOf(item));
        }
        Integer rowCount = adminMapper.deleteByIdArray(idList);
        if (rowCount > 0){
            map = Maps.newHashMap() ;
            map.put("msg","删除成功");
            return map ;
        }
        map = Maps.newHashMap() ;
        map.put("msg","删除失败");
        return map ;
    }

    public Map<String,Object> adminState(String id ,String adminState){
        Map<String,Object> map ;
        Integer adminId = Integer.valueOf(id);
        Integer state = Integer.valueOf(adminState);
        if (adminId == null){
            map = Maps.newHashMap() ;
            map.put("msg","id参数异常");
            return map ;
        }
        int rowCount = adminMapper.updateById(adminId, state);
        if (rowCount > 0){
            map = Maps.newHashMap() ;
            map.put("msg","更新状态成功");
            return map ;
        }
        map = Maps.newHashMap() ;
        map.put("msg","更新状态失败");
        return map ;
    }

    public Admin getAdminInfo(String id){
        if (StringUtils.isBlank(id)){
            logger.info("参数id异常");
        }
        Integer intId = Integer.valueOf(id);
        Admin admin = adminMapper.selectByPrimaryKey(intId);
        if (admin != null){
            admin.setaPassword(StringUtils.EMPTY);
            return admin;
        }
        return null ;
    }

    public List<Role> getRole(){
        List<Role> roles = roleMapper.selectByAll();
        if (roles.size() == 0){
            return null ;
        }
        return roles ;
    }

    public Map<String,Object> update(String aName,String aUsername,String roleId){
        Map<String,Object> map ;
        Integer intRoleId = Integer.valueOf(roleId);
        Admin admin = new Admin();
        admin.setaName(aName);
        admin.setaUsername(aUsername);
        admin.setRoleId(intRoleId);
        int rowCont = adminMapper.updateByPrimaryKeySelective(admin);
        if (rowCont > 0){
            map = Maps.newHashMap() ;
            map.put("success",true);
            return map ;
        }
        map = Maps.newHashMap() ;
        map.put("success",false);
        return map ;
    }

    /* admin-role */
    public PageInfo getRoleAdmin(int pageNum,int pageSize,Integer roleId){
        if (roleId != Const.AdminProfileType.DBA.getCode()){
            return null ;
        }
        String orderDesc = "role_id" + " desc";
        PageHelper.startPage(pageNum,pageSize,orderDesc);
        List<Role> roles = roleMapper.selectByAll();
        List<RoleAdminVo> adminVoList = Lists.newLinkedList();
        for (Role role : roles){
            RoleAdminVo roleAdminVo = assembleRoleAdminVo(role);
            adminVoList.add(roleAdminVo);
        }
        PageInfo pageInfo = new PageInfo(roles);
        pageInfo.setList(adminVoList);
        return pageInfo;
    }

    public List<Function> functionList(Integer roleId){
        Admin currentAdmin = RequestHolder.getCurrentAdmin();
        String md5Id = MD5Util.MD5EncodeUtf8(String.valueOf(currentAdmin.getaId()));
        String unique_ticket = currentAdmin.getaId()+md5Id+"_USER_LOGIN";
        String cacheDba = sysCacheService.getFromCache(Const.CacheKeyConstants.SYSTEM_ACLS,unique_ticket);
        if (StringUtils.isBlank(cacheDba)){
            List<RoleFunction> roleFunctionList = roleFunctionMapper.selectByRoleId(roleId);
            List functionLists = Lists.newArrayList();
            for (RoleFunction item : roleFunctionList){
                /* 查询父节点 */
                Function function = functionMapper.selectByFunctionId(item.getfId());
                FunctionAdminVo functionAdminVo = null ;
                if (function != null){
                    functionAdminVo = new FunctionAdminVo();
                    functionAdminVo.setfId(function.getfId());
                    functionAdminVo.setfName(function.getfName());
                    functionAdminVo.setParentId(function.getParentId());
                    functionAdminVo.setfUrl(function.getfUrl());
                    functionAdminVo.setfStatus(function.getfStatus());
                    List<Function> functionList = functionMapper.selectChildFunctionByParentId(item.getfId());
                    if (CollectionUtils.isNotEmpty(functionList)){
                        functionAdminVo.setFunctionList(functionList);
                    }
                }
                functionLists.add(functionAdminVo);
            }
            if (CollectionUtils.isNotEmpty(functionLists)){
                sysCacheService.saveCache(JsonMapper.obj2String(functionLists),
                        600 ,
                        Const.CacheKeyConstants.SYSTEM_ACLS,unique_ticket);
            }
            return functionLists;
        }
        return JsonMapper.string2Obj(cacheDba, new TypeReference<List>() {});
    }

    public JsonData deletedChange(Integer id , Integer deleted){
        Integer integer = adminMapper.updateByDeleted(id, deleted);
        if (integer != null){
            return JsonData.success();
        }
        return JsonData.fail("恢复管理员失败");
    }

    public JsonData del(Integer id){
        Integer rowCount = adminMapper.deleteAdminById(id);
        if (rowCount == null){
            return JsonData.fail("删除失败!");
        }
        return JsonData.success();
    }

    public JsonData roleDelete(Integer id){
        Integer rowCount = roleMapper.deleteRoleById(id);
        if (rowCount == null){
            return JsonData.fail("删除角色失败");
        }
        return JsonData.success();
    }


    /**
     * 判断当前用户是否是超级管理员权限
     * @param adminId
     * @return
     */
    public boolean isSuperRole(Integer adminId){
        if (adminId == null){
            return false ;
        }
        int rowCount = adminMapper.selectValidByAdminId(adminId);
        if (rowCount == Const.AdminProfileType.DBA.getCode()){
            return true ;
        }
        return false ;
    }

    /**
     * 封装角色对应的用户名
     * @param role
     * @return
     */
    private RoleAdminVo assembleRoleAdminVo(Role role){
        RoleAdminVo roleAdminVo = new RoleAdminVo();
        roleAdminVo.setRoleId(role.getRoleId());
        if (Const.AdminProfileType.DBA.getCode() == role.getRoleId()){
            roleAdminVo.setRoleName(Const.AdminProfileType.DBA.getDest());
        }else if (Const.AdminProfileType.ADMIN.getCode() == role.getRoleId()){
            roleAdminVo.setRoleName(Const.AdminProfileType.ADMIN.getDest());
        }else if (Const.AdminProfileType.USER.getCode() == role.getRoleId()){
            roleAdminVo.setRoleName(Const.AdminProfileType.USER.getDest());
        }else {
            String roleName = role.getRoleName();
            logger.info(roleName);
            roleAdminVo.setRoleName(role.getRoleName());
        }
        List<Admin> admins = adminMapper.selectByRoleId(role.getRoleId());
        List<String> adminNameList = Lists.newArrayList();
        for (Admin admin : admins){
            adminNameList.add(admin.getaName());
        }
        roleAdminVo.setAdminName(adminNameList);
        return roleAdminVo;
    }

    /**
     * 封装admin信息
     * @param admin
     * @return
     */
    private AdminInfoVo assembleAdminVo(Admin admin){
        AdminInfoVo adminInfoVo = new AdminInfoVo();
        adminInfoVo.setaId(admin.getaId());
        adminInfoVo.setaUsername(admin.getaUsername());
        adminInfoVo.setaName(admin.getaName());
        adminInfoVo.setaPassword(StringUtils.EMPTY);
        if (admin.getRoleId() == 1){
            adminInfoVo.setRole(Const.AdminProfileType.ADMIN.getDest());
        }else if (admin.getRoleId() == 0){
            adminInfoVo.setRole(Const.AdminProfileType.DBA.getDest());
        }
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime=formatter.format(admin.getaCreateTime());
        adminInfoVo.setaCreateTime(createTime);
        if (admin.getaUpdateTime() == null){
            adminInfoVo.setaUpdateTime("无");
        }else{
            String updateTime=formatter.format(admin.getaUpdateTime());
            adminInfoVo.setaUpdateTime(updateTime);
        }
        if (admin.getState() == Const.StateCode.ACTIVE.getCode()){
            adminInfoVo.setState(Const.StateCode.ACTIVE.getDest());
        }else if (admin.getState() == Const.StateCode.INACTIVE.getCode()){
            adminInfoVo.setState(Const.StateCode.INACTIVE.getDest());
        }
        if (admin.getDeleted() != null){
            adminInfoVo.setDeleted("已删除");
        }
        return adminInfoVo;
    }


}
